package com.byl.qrobot.util;

/**
 * Created by baiyuliang on 2016-5-13.
 */
import android.util.Log;

import com.byl.qrobot.bean.Music;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 百度音乐搜索API操作类
 */
public class MusicSearchUtil {
    private static final String TAG ="" ;

    /**
     * 根据名称和作者搜索音乐(注意此方法阻塞线程，调用时放在线程中)
     *
     * @param musicTitle 音乐名称
     * @param page
     * @return Music
     */
    public static Music searchMusic(String musicTitle, String page) {
        // 百度音乐搜索地址
        //String requestUrl = "http://box.zhangmen.baidu.com/x?op=12&count=1&title={TITLE}$${AUTHOR}$$$$";
        // 网易云音乐搜索地址
        String requestUrl = "http://47.94.11.81:8000/musicsearch/?name={TITLE}&page={page}&typename=netease";
        // 对音乐名称、作者进URL编码
        requestUrl = requestUrl.replace("{TITLE}", urlEncodeUTF8(musicTitle));
        requestUrl = requestUrl.replace("{page}", urlEncodeUTF8(page));
        // 处理名称、作者中间的空格
        requestUrl = requestUrl.replaceAll("\\+", "%20");

        // 查询并获取返回结果
        InputStream inputStream = httpRequest(requestUrl);
        // 从返回结果中解析出Music
        Music music = parseMusic(inputStream);

        return music;
    }


    public static List<Music> searchMusicList(String musicTitle, String page) {
        // 百度音乐搜索地址
        //String requestUrl = "http://box.zhangmen.baidu.com/x?op=12&count=1&title={TITLE}$${AUTHOR}$$$$";
        // 网易云音乐搜索地址
        String requestUrl = "http://47.94.11.81:8000/musicsearch/?name={TITLE}&page={page}&typename=netease";
        // 对音乐名称、作者进URL编码
        requestUrl = requestUrl.replace("{TITLE}", urlEncodeUTF8(musicTitle));
        requestUrl = requestUrl.replace("{page}", urlEncodeUTF8(page));
        // 处理名称、作者中间的空格
        requestUrl = requestUrl.replaceAll("\\+", "%20");

        // 查询并获取返回结果
        InputStream inputStream = httpRequest(requestUrl);
        // 从返回结果中解析出Music
        List<Music> list = parseMusicList(inputStream);

        return list;
    }


    /**
     * UTF-8编码
     *
     * @param source
     * @return
     */
    private static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送http请求取得返回的输入流
     *
     * @param requestUrl 请求地址
     * @return InputStream
     */
    private static InputStream httpRequest(String requestUrl) {
        InputStream inputStream = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            // 获得返回的输入流
            inputStream = httpUrlConn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 解析音乐参数
     *
     * @param inputStream 百度音乐搜索API返回的输入流
     * @return Music
     */
    @SuppressWarnings("unchecked")
    private static Music parseMusic(InputStream inputStream) {
        Music music = null;
        try {
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String str = sb.toString();
            System.out.println("输出" + str);

            JSONObject jsonObjectALL = new JSONObject(str);
            // 通过标识(person)，获取JSON数组
            JSONArray jsonArray = jsonObjectALL.getJSONArray("data");
            /*
            for (int i = 0; i < jsonArray.length(); i++) {
                // JSON数组里面的具体-JSON对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String title = jsonObject.optString("title", null);
                String url = jsonObject.optString("url", null);
                String author = jsonObject.optString("author", null);
                System.out.println("------------------");
                System.out.println("title" + title);
                System.out.println("url" + url);
                System.out.println("author" + author);

            }
             */
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            String title = jsonObject.optString("title", null);
            String url = jsonObject.optString("url", null);
            String author = jsonObject.optString("author", null);
            System.out.println("------------------");
            System.out.println("title" + title);
            System.out.println("url" + url);
            System.out.println("author" + author);
            music = new Music();
            music.setMusicUrl(url);
            //设置高品质音乐链接
            music.setHQMusicUrl(url);
            music.setTitle(title);
            music.setDescription(author);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return music;
    }
    private static List<Music> parseMusicList(InputStream inputStream) {
        List<Music> list = new ArrayList<Music>();

        try {
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String str = sb.toString();
            System.out.println("输出" + str);

            JSONObject jsonObjectALL = new JSONObject(str);
            // 通过标识(person)，获取JSON数组
            JSONArray jsonArray = jsonObjectALL.getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {
                // JSON数组里面的具体-JSON对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String title = jsonObject.optString("title", null);
                String url = jsonObject.optString("url", null);
                String author = jsonObject.optString("author", null);

                Music music = new Music();
                music.setMusicUrl(url);
                //设置高品质音乐链接
                music.setHQMusicUrl(url);
                music.setTitle(title);
                music.setDescription(author);
                list.add(music);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}